<?php

class SiteController extends Controller
{
        public function filters(){
            return array(
                array(
                    'application.filters.RequireLoginFilter - forgetpassword,captcha,mobilelogin,mobilelogout,login,logout',
                ),
            );
        }
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
        public function actionDownload($filename){
		$filename = urldecode($filename);
		Yii::app()->fileHelper->forceDownload($filename);
	}
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
               
		$this->render('index',array(
                    
                ));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
      
        $this->layout='//layouts/space';
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
                $loginfail=false;
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
                            $this->redirect(Yii::app()->user->returnUrl);
                        }else{
                            $loginfail=true;
                        }
				
		}
		// display the login form
		$this->render('newLogin',array(
                    'model'=>$model,
                    'forgetpassword'=>new ForgetPassword,
                    'loginfail'=>$loginfail
                    ));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect($this->createUrl('Site/login'));
	}
        public function actionForgetPassword(){
          
            $model=new ForgetPassword;
            $hasSent=false;
            $emailExist=false;
            $user=NULL;
            if(isset($_POST['ForgetPassword']) && isset($_POST['ajax']) && $_POST['ajax']=='forgetpassword-form'){
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
            if(isset($_POST['ForgetPassword'])){
                $model->attributes=$_POST['ForgetPassword'];
                $user=Users::model()->find('email =:e',array(
                    'e'=>$model->email
                ));
                
                if($user != NULL){
                    $to      = $user->email;
                    $newpassword=rand(0,999999999999);
                    $oldpassword=$user->password;
                    $user->password=$newpassword;
                    $subject = "Password change";
                    $message = "Hello $user->real_name, This is your new password from your password change request: $newpassword";
                    $headers = 'From: Customer Connect <do-not-reply@qsibanking.com>' . "\r\n" .
                        'Reply-To: Customer Connect <do-not-reply@qsibanking.com>' . "\r\n" .
                        "Bcc: $user->real_name <$user->email>" . "\r\n";
                        'X-Mailer: PHP/' . phpversion();

                    $result=mail($to, $subject, $message, $headers);
                    $passwordChange=new Passwordchanges();
                    $passwordChange->saveChange($user->id, $oldpassword);
                    if($result){
                        echo "Your email has been sent";
                        
                    }else{
                        echo "Problem when send email, please try again later";
                    }
                    Yii::app()->end();
               
                }
            }
            echo CActiveForm::validate($model);
                Yii::app()->end();
            
        }
        public function actionMobileLogin($username,$password,$deviceid){
            $users=getUserByPermission(Users::PRIVILEGE_MOBILE_LOGIN);
            if(in_array($username,$users)){
                $login=new LoginForm;
                $login->email=$username;
                $login->password=$password;
                $login->rememberMe=0;
                
                
                if($login->validate() && $login->login()){
                    $user=Users::model()->find('email=:email',array('email'=>$username));
                    
                    $user->updateAll(array(
                        'deviceid'=>$deviceid,
                        'mobileloggedin'=>1
                    ), 'email=:email'  , array('email'=>$username));
            
                    $rs=NULL;
                    
                    if($user->employeeid!=NULL && $user->custno==NULL){
                        $employee=Employees::model()->findByPk($user->employeeid);
                        $rs=array(
                            'warehouse'=>$employee->getAssignedWareHouse(),
                            'empno'=>$employee->empno,
                            'name'=>$employee->firstname.' '.$employee->lastname,
                            'imagelink'=>Yii::app()->request->getHostInfo().'/images/content/'.$employee->image,                            
                        );
                    }else if($user->custno!=NULL){
                        $customer=Customers::model()->findByPk($user->custno);
                        $rs=array(
                            'custno'=>$customer->custno,
                            'name'=>$customer->firstname.' '.$customer->lastname,
                            'image'=>Yii::app()->request->getHostInfo().'/images/content/'.$customer->image,
                        );
                    }
                    echo json_encode($rs);
                }
            }
        }
        public function actionMobileLogout(){
            $user=Users::model()->find('email=:email',array('email'=>Yii::app()->user->name));
            $user->updateAll(array(                        
                        'mobileloggedin'=>1
                    ), 'email=:email'  , array('email'=>$username));

            Yii::app()->user->logout();
        }
}
